/*
 * @Author: puhuaping
 * @Date: 2020-04-13 16:56:23
 */
<style lang="less" scoped>
.merchant-list {
  .btnBox {
    text-align: right;
  }
  .ivu-btn-small {
    padding: 1px 7px;
  }
  .ivu-btn {
    margin: 0 3px;
  }
}
.flex-table {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
}
</style>
<template>
  <div class="merchant-list">
    <Card :bordered="true">
      <Tabs value="name1" @on-click="bannerChange">
        <TabPane label="首页顶部" name="name1"></TabPane>
        <TabPane label="首页中部固定广告位" name="name2"></TabPane>
        <TabPane label="首页中部banner广告" name="name3"></TabPane>
        <TabPane label="门店服务顶部banner" name="name4"></TabPane>
        <TabPane label="商城顶部banner" name="name5"></TabPane>
        <TabPane label="商城中部banner" name="name6"></TabPane>
      </Tabs>
      <!-- 表格 -->
      <div class="flex-table">
        <span></span>
        <Button type="primary" @click="showModel=true">新增banner</Button>
      </div>
      <tables
        ref="tables"
        :columns="columns"
        search-place="top"
        :searchBtn="false"
        v-model="tableData"
      />
    </Card>
    <Modal
      :mask-closable="false"
      v-model="showModel"
      :title="curRowData?'编辑banner':'新增banner'"
      width="400"
      @on-visible-change="changeModel"
    >
      <Form
        ref="formSubmitRef"
        :model="formSubmitData"
        :rules="formSubmitRule"
        class="model-wrap"
        :label-width="90"
      >
        <FormItem label="banner图片" prop="imgUrl">
          <Upload
            ref="upload"
            :header="upimgheader"
            :data="params"
            :show-upload-list="false"
            :default-file-list="defaultList"
            :on-success="handleSuccess"
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :before-upload="handleBeforeUpload"
            type="drag"
            :action="postUrl"
            style="display: inline-block;width:58px;"
          >
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
          </Upload>
        </FormItem>
        <FormItem label="说明" prop="name">
          <Input placeholder="请输入" v-model="formSubmitData.name" />
        </FormItem>
        <FormItem label="排序" v-if="formSearch.type!=2" prop="orderNumber">
          <Input placeholder="请输入" v-model="formSubmitData.orderNumber" />
          <!-- <p>（序号越小约靠前）</p> -->
        </FormItem>
        <FormItem label="位置" v-if="formSearch.type==2" prop="orderNumber">
          <Select clearable style="width:180px">
            <Option value="WAIT_AUDIT">左边</Option>
            <Option value="AUDIT_PASS">右边</Option>
          </Select>
        </FormItem>
        <FormItem label="跳转类型" prop="typeRadio">
          <RadioGroup v-model="formSubmitData.typeRadio">
            <Radio label="1">内部资源</Radio>
            <Radio label="2">外部地址</Radio>
            <Radio label="3">不跳转</Radio>
          </RadioGroup>
        </FormItem>
        <div v-if="formSubmitData.typeRadio==1">
          <FormItem :label-width="80" prop="jumpType">
            <RadioGroup v-model="formSubmitData.jumpType">
              <Radio label="TO_GOODS">商品</Radio>
              <Radio label="TO_SITE">门店</Radio>
              <Radio label="TO_SERVICE">服务分类</Radio>
              <Radio label="TO_GOODS_CLASSIFY">商品分类</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem :label-width="80" prop="jumpValue">
            <Input placeholder="请输入内部资源对应的ID" v-model="formSubmitData.jumpValue" />
          </FormItem>
        </div>
        <FormItem
          :label-width="80"
          prop="jumpValue"
          v-model="formSubmitData.jumpValue"
          v-if="formSubmitData.typeRadio==2"
        >
          <Input placeholder="请输入外部地址URL" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="showModel=false">取消</Button>
        <Button type="primary" @click="sureModel">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import Tables from "@/components/tables/tables.vue";
import { requestData, getData } from "@/api/data";
import { setToken, getToken } from "@/libs/util";
import { isNumber } from "@/tool/validator";
import config from "@/config";
const baseUrl =
  process.env.NODE_ENV === "development"
    ? config.baseUrl.dev
    : config.baseUrl.pro;
export default {
  name: "userList",
  components: {
    Tables
  },
  data() {
    return {
      // 图片
      upimgheader: {
        // 文件上传的请求头设置
        headers: { "Content-Type": "	multipart/form-data" }
      },
      params: {
        token: getToken()
      },
      uploadList: [], // 商品封面默认图片文件上传
      defaultList: [],
      // 图片end
      showModel: false,
      curRowData: null,
      page: {},
      tableData: [],
      formSubmitRule: {
        typeRadio: [
          {
            required: true,
            message: "请选择",
            trigger: "blur"
          }
        ],
        jumpValue: [
          {
            required: true,
            message: "请输入",
            trigger: "blur"
          }
        ],
        jumpType: [
          {
            required: true,
            message: "请选择",
            trigger: "blur"
          }
        ],
        imgUrl: [
          {
            required: true,
            message: "请上传",
            trigger: "blur"
          }
        ],
        name: [
          {
            required: true,
            message: "请输入说明",
            trigger: "blur"
          }
        ],
        orderNumber: [
          {
            required: true,
            message: "请输入排序",
            trigger: "blur"
          }
        ]
      },
      formSearch: {
        type: 1
      },
      formSubmitData: {
        typeRadio: "1",
        jumpType: "",
        imgUrl: "",
        name: "",
        orderNumber: "",
        jumpValue: ""
      },
      columns: [
        {
          title: "bannerID",
          key: "id",
          minWidth: 100,
          align: "center"
        },
        {
          title: "说明",
          align: "center",
          key: "name",
          minWidth: 100
        },
        {
          title: "图片",
          align: "center",
          key: "imgUrl",
          minWidth: 120,
          render: (h, params) => {
            return h("img", {
              attrs: {
                src: params.row.imgUrl
              },
              style: {
                width: "120px",
                height: "60px"
              }
            });
          }
        },
        {
          title: "跳转类型",
          align: "center",
          key: "jumpType",
          minWidth: 100,
          render: (h, params) => {
            let text = {
              NONE: "不跳转",
              URL: "外部地址",
              GOODS: "商品",
              SERVICE: "服务分类"
            }[params.row.jumpType];
            return h("span", text);
          }
        },
        {
          title: "跳转链接",
          align: "center",
          key: "imgUrl",
          minWidth: 100
        },
        {
          title: "序号",
          align: "center",
          key: "orderNumber",
          minWidth: 100
        },
        {
          title: "状态",
          align: "center",
          key: "jumpType",
          minWidth: 100,
          render: (h, params) => {
            let text = {
              VALID: "启用",
              DISABLE: "禁用"
            }[params.row.state];
            return h("span", text);
          }
        },
        {
          title: " ",
          align: "center",
          key: ""
        },
        {
          title: "操作",
          align: "center",
          width: 180,
          fixed: "right",
          align: "center",
          render: (h, params) => {
            let text = params.row.state == "VALID" ? "下架" : "上架";
            return h("div", [
              h(
                "Button",
                {
                  attrs: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.showModel = true;
                      this.curRowData = params.row;
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  attrs: {
                    type: "success",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      let dataObj = {
                        id: params.row.id,
                        state: params.row.state == "VALID" ? "DISABLE" : "VALID"
                      };
                      requestData(
                        "/admin/user/updateState",
                        "post",
                        dataObj
                      ).then(res => {
                        if (res.data.code == 0) {
                          this.$Message.success("操作成功");
                          this.getListData();
                        } else {
                          this.$Message.error(res.data.msg);
                        }
                      });
                    }
                  }
                },
                text
              ),
              h(
                "Button",
                {
                  attrs: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: "提示",
                        width: "300",
                        content: "提示：确定删除该banner吗？",
                        onOk: () => {
                          let dataObj = {
                            id: params.row.id,
                            state: "DELETE"
                          };
                          requestData(
                            "/admin/banner/updateState",
                            "post",
                            dataObj
                          ).then(res => {
                            if (res.data.code == 0) {
                              this.$Message.success("操作成功");
                              this.getListData();
                            } else {
                              this.$Message.error(res.data.msg);
                            }
                          });
                        }
                      });
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ]
    };
  },
  computed: {
    postUrl() {
      return baseUrl + "/common/singleUpload" + `?token=${getToken()}`;
    }
  },
  methods: {
    //   banner切换
    bannerChange(nameVal) {
      let type = { name1: 1, name2: 2, name3: 3, name4: 4, name5: 5, name6: 6 }[
        nameVal
      ];
      this.formSearch.type = type;
      this.getListData();
    },
    // 文件上传成功的钩子
    handleSuccess(res, file) {
      //   this.formValidate.cover = res.data.path;
      file.url = res.data.path;
      this.uploadList.push(file);
    },
    // 文件格式验证失败的钩子
    handleFormatError(file) {
      this.$Notice.warning({
        title: "格式错误",
        desc: "只能上传jpg,jpeg,png格式,请检查图片格式"
      });
    },
    // 文件超出指定大小的钩子
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "文件大小超出规定",
        desc: "文件 " + file.name + " 太大了, 不能超过2M."
      });
    },
    // 上传之前的钩子
    handleBeforeUpload(file) {
      const check = this.uploadList.length < 1;
      if (!check) {
        this.$Notice.warning({
          title: "警告",
          desc: "只可以上传一张封面图片"
        });
      }
      //   && this.checkImageWH(file, 690, 356)
      return check;
    },
    checkImageWH(file, width, height) {
      let self = this;
      return new Promise(function(resolve, reject) {
        let filereader = new FileReader();
        filereader.onload = e => {
          let src = e.target.result;
          const image = new Image();
          image.onload = function() {
            if (width && this.width != width) {
              self.$Notice.error({
                title: "请上传宽为" + width + "的图片"
              });
              reject();
            } else if (height && this.height != height) {
              self.$Notice.error({
                title: "请上传高为" + height + "的图片"
              });
              reject();
            } else {
              resolve();
            }
          };
          image.onerror = reject;
          image.src = src;
        };
        filereader.readAsDataURL(file);
      });
    },
    //model确定
    sureModel() {
      this.$refs.formSubmitRef.validate(valid => {
        if (valid) {
          const curRowData = this.curRowData;
          let dataObj = {
            id: curRowData.id,
            remark: this.formSubmitData.remark,
            pass: false
          };
          requestData(
            "/admin/mall/orderAfterSales/audit",
            "post",
            dataObj
          ).then(res => {
            if (res.data.code == 0) {
              this.$Message.success("操作成功");
              this.showModel = false;
              this.getListData();
            } else {
              this.$Message.error(res.data.msg);
            }
            this.showModel = false;
          });
        }
      });
    },
    // form初始化
    inintFormSubmit() {
      this.formSubmitData = {
        typeRadio: "1",
        jumpType: "",
        imgUrl: "",
        name: "",
        orderNumber: "",
        jumpValue: ""
      };
    },

    //模态框改变
    changeModel(e) {
      if (!e) {
        this.curRowData = null;
        this.inintFormSubmit();
      }
    },
    getListData() {
      const dataObj = Object.assign(
        {
          page: this.indexPage,
          max: 10
        },
        this.formSearch
      );
      requestData("/admin/banner", "get", dataObj).then(res => {
        if (res.data.code == 0) {
          const { pageNumber, totalPage, totalRow } = res.data.page;
          this.page = {
            pageNumber: pageNumber,
            totalPage,
            totalRow: totalRow
          };
          this.tableData = res.data.data || [];
        } else {
          this.$Message.error(res.data.msg);
        }
      });
    }
  },
  mounted() {
    this.getListData();
  }
};
</script>
